<?php
/**
 * 微信授权类
 * User: narnia
 * Date: 2017/5/19
 * Time: 11:24
 */
namespace LancerWechat;
class WechatOauth extends WechatService
{
    /**
     * @var 标识
     */
    public $key = 'oauth';
    /**
     * @var 回调code码
     */
    public $code;
    /**
     * @var 用户信息
     */
    public $user;


    /**
     * 跳转获取code
     */
    public function redirect()
    {
        $redirectUri = urlencode($this->config[$this->key]['redirectUri']);
        // 获取code url
        $url = $this->getUrl([
            '{appid}' => $this->config['global']['appid'],
            '{redirectUri}' => $redirectUri,
            '{scope}' => $this->config[$this->key]['scope'],
            '{state}' => isset($this->config[$this->key]['state']) ? : 'STATE',
        ], [$this->key, 'code']);
        header("Location: " . $url);
    }

    /**
     * 此方法必须执行一次
     *  获取回调code
     */
    public function getCode()
    {
        $this->code = isset($_GET['code']) ? $_GET['code'] : null;
        return $this->code;
    }

    /**
     * 获取网页授权的用户信息
     * @return mixed 用户对象
     */
    public function getUser($getInfo = false)
    {
        $url = $this->getUrl([
            '{appid}' => $this->config['global']['appid'],
            '{secret}' => $this->config['global']['appsecret'],
            '{code}' => $this->code
        ], [$this->key, 'access_token']);
        $result = json_decode(\LancerWechat\WechatFunction::curl($url));
        if ($getInfo) {
            if (isset($result->access_token)) {
                // 获取用户信息
                $url = $this->getUrl([
                    '{access_token}' => $result->access_token,
                    '{openid}' => $result->openid
                ], [$this->key, 'user']);
                $result = json_decode(\LancerWechat\WechatFunction::curl($url));
            }
        }
        // 日志
        \LancerWechat\WechatLog::write($this->config['log']['path'], $result);
        return $result;
    }

}